%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Creates matrices for VAR(k) and trend - version 21.4.06

% input:
% y is data
% c constant or trend (c=0: no constant; c=1: constant; c>=2: time trend with c-1 breaks)
% the vector trendbreak contains the breakpoints
% k is number of lags
% do_boot is an option for bootstrap intervals, default is zero

% output:
% yy LHS variables
% xx RHS variables
% x RHS variables, differently stacked


function [yy,xx,x] = VAR_lagtrend(y,c,trendbreak,k,do_boot)

s = size(y);    % size of dataset
T = s(1);       % length of sample
N = s(2);       % number of variables

for i=1:N,
    yy(:,i)=y(k+1:T,i); % LHS; keep lags for regressors
    for j=1:k,
        xx(:,k*(i-1)+j)=y(k+1-j:T-j,i); % RHS regressors
        % stacking all lags of first variable, then all lags of second,
        % etc.
    end; 
end;

if c==0,
    xx=xx;
elseif c==1,
    xx=[ones(T-k,1) xx];
elseif c>=2,
    dum = zeros(T-k,c);
    if do_boot == 1
        dum(1:trendbreak(1)-2*k,1) = ones(trendbreak(1)-2*k,1);
        for j=2:c-1,
            dum(trendbreak(j-1)+1-2*k:trendbreak(j)-2*k,j) = ones(trendbreak(j)-trendbreak(j-1),1);
        end;
        dum(trendbreak(c-1)+1-2*k:end,c) = ones(T+k-trendbreak(c-1),1);
    else
        dum(1:trendbreak(1)-k,1) = ones(trendbreak(1)-k,1);
        for j=2:c-1,
            dum(trendbreak(j-1)+1-k:trendbreak(j)-k,j) = ones(trendbreak(j)-trendbreak(j-1),1);
        end;
        dum(trendbreak(c-1)+1-k:end,c) = ones(T-trendbreak(c-1),1);
    end;
    xx= [dum  xx];
end

% sorting differently
for ij = 1:k
    zz(:,(ij-1)*N+1:N*ij) = xx(:,ij+c:k:size(xx,2));
    % stacking lag one of all variables, then lag two, etc.
    % ij+c:k:size(xx,2) takes out every kth element up to the full size
    % starting after constant
end
if c==0 
    x=zz;
else
    z(:,1:c)=xx(:,1:c); % constant stays the same
    x = [z zz];
end